package com.example.connor.nfc_smartlock_androidapp;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.content.Context;
import android.nfc.*;
import android.widget.ImageView;

import java.io.Console;
import java.io.File;


public class MainActivity extends ActionBarActivity {

    private static ImageView main_icon; //button object
    private static boolean hasLock;  //bool to hold the state
    private NfcManager nfc_manager; //nfc manager
    private NfcAdapter nfc_adapter; //nfc adapter
    private static SecurePreferences s_preference;
    private static AlertDialog.Builder nfc_builder;
    private static AlertDialog.Builder error_builder;
    private static AlertDialog.Builder wipe_builder;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        s_preference = new SecurePreferences(this,"msp", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID), true ); //Initialize secure preferences
        nfc_manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE); //Initialize manager
        nfc_adapter = nfc_manager.getDefaultAdapter(); //Initialize adapter
        main_icon = (ImageView)findViewById(R.id.main_icon); //Initialize main icon
        nfc_builder = new AlertDialog.Builder(this);
        error_builder = new AlertDialog.Builder(this);
        wipe_builder = new AlertDialog.Builder(this);

        hasLock = false; //guess hasLock is false here check later
        if(nfc_adapter != null && nfc_adapter.isEnabled()) { //check that user has nfc enabled
            String Key = this.getKey();
            if(Key != "Empty00000000000") //If there is no key temp key should be "Empty"
            {
                hasLock = true; //if it's not than hasLock is true
            }
            if (hasLock) {
                iconImageLock();
            } else {
                iconImageUnlock();
            }
        }
       else
       {
           popupNFC();
       }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        if(nfc_adapter != null && nfc_adapter.isEnabled()) { //check that user has nfc enabled
            Log.d("Debug:", "Passed");
            String Key = this.getKey();
            if(Key != "Empty00000000000") //If there is no key temp key should be "Empty"
            {
                hasLock = true; //if it's not than hasLock is true
            }
            if (hasLock) {
                iconImageLock();
            } else {
                iconImageUnlock();
            }
        }
        else
        {
            Log.d("Debug", "Failed");
            popupNFC();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_wipe_key) {
            popupWipeKey();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    ///
    ///This Function is for changing the main icon to the Lock icon
    ///
    private static void iconImageLock() {
       // button.setText(R.string.lock);
        main_icon.setImageResource(R.drawable.icon_lock);
    }

    ///
    ///This Function is for changing the main icon to the Unlock icon
    ///
    private static void iconImageUnlock() {
       // button.setText(R.string.unlock);
        main_icon.setImageResource(R.drawable.icon_unlock);
    }

    ///
    ///This function is for creating a popup forcing the user to turn on NFC
    ///
    private void popupNFC() {


        nfc_builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
                dialog.dismiss();

            }
        });

/*        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
            }
        });*/

        nfc_builder.setMessage(R.string.nfc_tooltip).setTitle(R.string.nfc_off);

        AlertDialog dialog = nfc_builder.create();

        dialog.show();
    }

    ///
    ///This function creates and displays an error popup
    ///
    /// Variable int i is a flag used to determine the message that should be popped
    protected static void popupError(int i) {

        error_builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        ///when i is 0 display the access denied message else send the unavailable
        switch(i)
        {
            case 0: error_builder.setMessage(R.string.access_denied_tip).setTitle(R.string.access_denied);
                    break;
            default: error_builder.setMessage(R.string.unavailable_tip).setTitle(R.string.unavailable);
                    break;
        }

        AlertDialog dialog = error_builder.create();

        dialog.show();
    }

    ///
    ///This function creates a popup allowing the user to wipe the key they have
    ///
    private static void popupWipeKey() {
        wipe_builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MainActivity.toUnlockState();
                dialog.dismiss();
            }
        });
        wipe_builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        wipe_builder.setMessage("Clearing the Key will make you unable to access the locker").setTitle("WARNING");

        AlertDialog dialog = wipe_builder.create();

        dialog.show();
    }

    ///
    ///This function returns the key it has in Stored Preferences
    ///
    protected static String getKey() {
        return s_preference.getString("Key Value");
    }

    ///
    ///This function clears the shared preferences of the app, deleting the key
    ///
    private static void clearPreference() {
        s_preference.clear();
    }

    ///
    ///This function sets the shared preferences of the app, saving the key
    ///
    ///variable String value is the key string
    private static void setPreference(String value) {
        s_preference.put("Key Value", value);
    }

    ///
    ///This function gives the nfc layer the ability to change to the lock state
    ///
    protected static void toLockState(String value) {
        setPreference(value);
        iconImageLock();
        hasLock = true;
    }

    ///
    ///This function gives the nfc layer the ability to change to the unlock state
    ///
    protected static void toUnlockState() {
        clearPreference();
        iconImageUnlock();
        hasLock = false;
    }
}
